Introduction to programming with Python

CorrelAidXKonstanz

What is programming?

Easy syntax

C++:

#include <iostream>

float fahrenheit_to_celsius(float fahrenheit) {
    float celsius = (fahrenheit - 32) * 5 / 9;
    return celsius;
}

int main() {
    std::cout << fahrenheit_to_celsius(-40) << std::endl;
}

Python:

def fahrenheit_to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius

print(fahrenheit_to_celsius(-40))

Variables

Variables are like containers that store information we want to use later, like a name tag for data. Variable assignment is when we create a variable and give it a value. In Python, we assign variables using =:

age = 25
name = "Klaus"

We can now refer to these values by name & reuse them anywhere in our code.

Data types

type description example
str text (string) "Hello Wold"
int integer number 5
float number with decimal places (“floating point”) 2.5
bool True or False (“Boolean”) True
None No type

We can perform different types of operations on different types of data, like doing calculations with numbers, or pasting together text. In programming languages, this is reflected in the concept of “data types”.

Strings

strings are Python’s way of representing text. Everything within quotes (“” or ’’) will be interpreted by Python as text:

a_string = "This is a string!"
also_a_string = 'This is also a string!'

Numeric types (int and float)

“Numbers” in Python support these kinds of arithmetic operations:

Symbol Task Performed
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor division (cut off decimal places/round down)
% Modulus (division remainder)
** Exponentiation

Floating point error

Due to how floating point numbers are represented internally, there are sometimes small inaccuracies in floating point arithmetic with some numbers that can’t be represented entirely accurately:

0.1 + 0.2
0.30000000000000004